﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Contract.Domain;
using Framework.Domain;
using System.Reflection;
using MySql.Data.MySqlClient;
using System.Configuration;

namespace CIIS.Common
{
    public class DataUtils
    {
        public static readonly DataUtils Instance = new DataUtils();
        private string connetString
        {
            get
            {
                ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["mysql"];
                return settings.ConnectionString;
            }
        }
        public void ExcutExecuteNonQuery(MySqlCommand cmd)
        {
            try
            {
                if (cnn.State == System.Data.ConnectionState.Closed)
                {
                    cnn.Open();
                }
                cmd.Connection = cnn;
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cnn.Close();
            }
        }
        private MySqlConnection _cnn;
        public MySql.Data.MySqlClient.MySqlConnection cnn
        {
            get
            {
                if (_cnn == null)
                {
                    _cnn = new MySqlConnection();
                    _cnn.ConnectionString = connetString;
                }
                return _cnn;
            }
        }
       
        DataUtils()
        {
        }

        private Contract.IService.IDaoService _dao;
        public Contract.IService.IDaoService Dao
        {
            get
            {
                try
                {
                    if (_dao == null)
                    {
                        _dao = (Contract.IService.IDaoService)ctx["DaoService"];
                    }
                    return _dao;
                }
                catch
                {
                    return null;
                }
            }
            set
            {
                _dao = value;
            }
        }

        private Spring.Caching.ICache cache;
        public Spring.Caching.ICache SpringCache
        {
            get
            {

                if (cache == null)
                    cache = (Spring.Caching.ICache)ctx.GetObject("AspNetCache");
                return cache;
            }
            set
            {
                cache = value;
            }
        }
        private Spring.Context.IApplicationContext _ctx;
        protected Spring.Context.IApplicationContext ctx
        {
            get
            {
                try
                {
                    if (_ctx == null)
                        _ctx = Spring.Context.Support.ContextRegistry.GetContext();
                    return _ctx;
                }
                catch
                {
                    return null;
                }
            }
        }

        #region 数据及缓存操作
        IList GetDataList<T>()
        {
            return Utils.Instance.GetDataList<T>(Dao);
        }

        IList GetDataList(string tableName)
        {
            return Utils.Instance.GetDataList(Dao, tableName);
        }

        List<bm_tq_jg> province = null;
        public List<bm_tq_jg> GetProvince()
        {
            if (province == null)
            {
                province = new List<bm_tq_jg>();
                IList allJg = GetDataList<bm_tq_jg>();
                for (int i = 0; i < allJg.Count; i++)
                {
                    bm_tq_jg jg = allJg[i] as bm_tq_jg;
                    if (jg != null)
                    {
                        if (jg.BH0000.EndsWith("0000"))
                        {
                            province.Add(jg);
                        }
                    }
                }
            }
            return province;
        }

        public List<bm_tq_jg> GetCity(string provinceId)
        {
            List<bm_tq_jg> city = new List<bm_tq_jg>();
            IList allJg = GetDataList<bm_tq_jg>();
            for (int i = 0; i < allJg.Count; i++)
            {
                bm_tq_jg jg = allJg[i] as bm_tq_jg;
                if (jg != null)
                {
                    if (jg.BH0000.EndsWith("00")
                        && !jg.BH0000.EndsWith("0000")
                        && jg.BH0000.StartsWith(provinceId.Substring(0, 2)))
                    {
                        city.Add(jg);
                    }
                }
            }
            return city;
        }

        public List<bm_tq_jg> GetCounty(string cityId)
        {
            List<bm_tq_jg> county = new List<bm_tq_jg>();
            IList allJg = GetDataList<bm_tq_jg>();
            for (int i = 0; i < allJg.Count; i++)
            {
                bm_tq_jg jg = allJg[i] as bm_tq_jg;
                if (jg != null)
                {
                    if (!jg.BH0000.EndsWith("00")
                        && !jg.BH0000.EndsWith("0000")
                        && jg.BH0000.StartsWith(cityId.Substring(0, 4)))
                    {
                        county.Add(jg);
                    }
                }
            }
            return county;
        }

        public string[] GetAddressCode(string[] address)
        {
            if (address == null || address.Length == 0)
            {
                return null;
            }
            string[] codes = new string[address.Length];
            for (int i = 0; i < address.Length; i++)
            {
                codes[i] = string.Empty;
                IList jgList = GetDataList<bm_tq_jg>();
                for (int j = 0; j < jgList.Count; j++)
                {
                    bm_tq_jg jg = jgList[j] as bm_tq_jg;
                    if (jg != null && jg.MC0000.Trim() == address[i].Trim())
                    {
                        codes[i] = jg.BH0000;
                        break;
                    }
                }
            }
            return codes;
        }

        Dictionary<string, IList> listDictionary = new Dictionary<string, IList>();
        /// <summary>
        /// 从缓存中读数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IList GetListFromCache(string tableName)
        {
            IList dataList = null;
            if (listDictionary.ContainsKey(tableName))
            {
                dataList = listDictionary[tableName];
            }
            else
            {
                dataList = GetDataList(tableName);
                listDictionary[tableName] = dataList;
            }
            return dataList;
        }
        public IList GetListFromCache<T>() where T : Entity
        {
            return GetListFromCache(typeof(T).Name);
        }

        /// <summary>
        /// 重新加载数据，将旧数据从缓存中清除，再从数据库中重新读取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IList ReloadDataList(string tableName)
        {
            if (listDictionary.ContainsKey(tableName))
            {
                listDictionary.Remove(tableName);
            }

            return GetListFromCache(tableName);
        }
        public IList ReloadDataList<T>() where T : Entity
        {
            return ReloadDataList(typeof(T).Name);
        }

        #endregion

        #region 下拉框绑定参数
        Dictionary<string, DropdownControlParam> dcpDictionary = new Dictionary<string, DropdownControlParam>();
        /// <summary>
        /// 仅提供基础字典表的下拉参数
        /// </summary>
        /// <param name="baseTableName"></param>
        /// <returns></returns>
        public DropdownControlParam GetDropdownControlParam(string baseTableName)
        {
            if (baseTableName.StartsWith("bm_"))
            {
                DropdownControlParam dcp = new DropdownControlParam() { ValueMember = "BH0000", DisplayMember = "MC0000", Caption = string.Empty, DataSource = GetListFromCache(baseTableName) };
                return dcp;
            }
            else
            {
                return null;
            }
        }
        public DropdownControlParam GetDropdownControlParam<T>() where T : Entity
        {
            return GetDropdownControlParam(typeof(T).Name);
        }

        public DropdownControlParam GetProvinceDcp()
        {
            DropdownControlParam dcp = new DropdownControlParam()
            {
                ValueMember = "BH0000",
                DisplayMember = "MC0000",
                NullText = "选择省份",
                Caption = "选择省份",
                DataSource = GetProvince()
            };
            return dcp;
        }

        public DropdownControlParam GetCityDcp(string provinceId)
        {
            DropdownControlParam dcp = new DropdownControlParam()
            {
                ValueMember = "BH0000",
                DisplayMember = "MC0000",
                NullText = "选择地市",
                Caption = "选择地市",
                DataSource = GetCity(provinceId)
            };
            return dcp;
        }

        public DropdownControlParam GetCountyDcp(string cityId)
        {
            DropdownControlParam dcp = new DropdownControlParam()
            {
                ValueMember = "BH0000",
                DisplayMember = "MC0000",
                NullText = "选择区县",
                Caption = "选择区县",
                DataSource = GetCounty(cityId)
            };
            return dcp;
        }

        /// <summary>
        /// 单位下拉绑定
        /// </summary>
        public DropdownControlParam OfficeDcp
        {
            get { return new DropdownControlParam() { ValueMember = "MJJH", DisplayMember = "XM", DataSource = GetListFromCache<t_sys_mjxx>() }; }
        }

        /// <summary>
        /// 使用民警下拉绑定
        /// </summary>
        public DropdownControlParam SymjDcp
        {
            get { return new DropdownControlParam() { ValueMember = "BH", DisplayMember = "NAME", DataSource = GetListFromCache<Office>() }; }
        }

        /// <summary>
        /// 领导下拉绑定
        /// </summary>
        public DropdownControlParam UserDcp
        {
            get { return new DropdownControlParam() { ValueMember = "UserCode", DisplayMember = "USER_NAME", DataSource = GetListFromCache<t_sys_user>() }; }
        }

        /// <summary>
        /// 侦查阵地下拉绑定
        /// </summary>
        public DropdownControlParam ZczdDcp
        {
            get { return new DropdownControlParam() { ValueMember = "Id", DisplayMember = "ZKD_MC", DataSource = GetListFromCache<t_tq_zczd>() }; }
        }

        /// <summary>
        /// 特情人员
        /// </summary>
        public DropdownControlParam TqryDcp
        {
            get { return new DropdownControlParam() { Caption = "选择特情人员", DataSource = GetListFromCache<t_tq_tqry>(), DisplayMember = "XM", ValueMember = "RYDH" }; }
        }
        #endregion


    }
}
